import { FirstComponent } from './../first/first.component';
import {
  Component,
  OnInit, ViewChild, ViewContainerRef, ComponentFactoryResolver, ComponentFactory, ComponentRef, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-dynamic-container',
  templateUrl: './dynamic-container.component.html',
  styleUrls: ['./dynamic-container.component.css']
})
export class DynamicContainerComponent implements OnInit, OnDestroy {

  componentRef: ComponentRef<any>;

  @ViewChild('viewContainerRef', { read: ViewContainerRef }) viewContainerRef: ViewContainerRef;

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver
  ) { }

  ngOnInit() {
  }

  createComponent() {
    this.viewContainerRef.clear();
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(FirstComponent);
    this.componentRef = this.viewContainerRef.createComponent(componentFactory);
    // componentRef.instance.data = {obj: 'inputData'};
  }

  delComponent() {
    this.componentRef.destroy();
  }

  ngOnDestroy(): void {
    this.componentRef.destroy();
  }

}
